#!/bin/bash

: ${DRY_RUN:=false}
: ${DEBUG:=1}
: ${EVENT_LOG_DIR=/tmp}

EVENT_LOG=$EVENT_LOG_DIR/serf-ambari-$(date +%Y%m%d-%H%M).log

debug() {
  [ $DEBUG -gt 0 ] && echo [DEBUG] "$@" 1>&2
}

run-command-unless-dry-run() {
  CMD="$@"
  if [ "$DRY_RUN" == "false" ]; then
    debug "$CMD"
    "$@"
  else
    debug [DRY_RUN] "$CMD"
  fi
}

# save serf-event into file, to be able to process multiple times
cat > $EVENT_LOG

# if I am server and I am listed in the member-join event: start server
if [[ "member-join" == "$SERF_EVENT" ]] && grep "$SERF_SELF_NAME" $EVENT_LOG &> /dev/null ; then
  if [[ "$SERF_TAG_AMBARI_SERVER" == "true" ]] ;then
    run-command-unless-dry-run ambari-server start
  fi
fi

# if there is a server joing and I am an agent: start agent
if [[ "$SERF_TAG_AMBARI_AGENT" == "true" ]];then
  if grep 'ambari-server=true' $EVENT_LOG &> /dev/null; then
    AMBARI_SERVER=$(grep 'ambari-server=true' $EVENT_LOG|cut -f 1)
    run-command-unless-dry-run sed -i.bak "/^hostname=/ s/.*/hostname=${AMBARI_SERVER}/" /etc/ambari-agent/conf/ambari-agent.ini
    run-command-unless-dry-run ambari-agent start
  fi
fi
